﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using SLLottery.Common;
using SLLottery.Controls;
using SLLottery.LotterySrv;
using System.ComponentModel;
namespace SLLottery
{
	public partial class MainPage : UserControl
	{
		Socket skt;//客户端 Socket
		SocketAsyncEventArgs SendArgs = new SocketAsyncEventArgs();//Socket异步操作所需的参数对象      
		byte[] ReceiveBytes = new byte[1024];
		private LotterySrv.LotteryServiceClient _srvProxy;
		private bool MakeOffLine = false;
		//====
		public static Popup _tip = new Popup();
		public static StackPanel sp = new StackPanel();
		public static Grid _layRoot;
		public static MediaElement media;
		//=====
		public static StackPanel stkP;
		public static StackPanel stkR;
		//===
		public static bool IsFengDan = false;
		public static int kaijiangState;
		public static MainBet mainBet;
		public static LotteryType lotteryType;
		public static LotteryType lotteryTypeAll;
		public static int playType = 0;
		public static int playTypeRadio = 0;
		public static Grid PersonalControl;
		public static Controls.TouZhuCtrl TouzhuControl;
		private DispatcherTimer RefreshTimer;
		public static List<RateGrid> rateGrids;
		public static DispatcherTimer kaijiang_timer;
		public static Dictionary<string, int> dicWs = new Dictionary<string, int>();
		public MainPage()
		{
			InitializeComponent();
			PersonalControl = this.gridUserInfo;
			_layRoot = this.LayoutRoot;
			CreateVodio();
			_srvProxy = WcfProxy.GetProxy;
			RefreshTimer = new DispatcherTimer();
			RefreshTimer.Interval = TimeSpan.FromSeconds(40);
			RefreshTimer.Tick += new EventHandler(RefreshTimer_Tick);
			this.Loaded += new RoutedEventHandler(MainPage_Loaded);
			LayoutRoot.SizeChanged += new SizeChangedEventHandler(LayoutRoot_SizeChanged);
			_srvProxy.GetBankInfoCompleted += new EventHandler<GetBankInfoCompletedEventArgs>(_srvProxy_GetBankInfoCompleted);
			_srvProxy.GetLotteryTypeCompleted += new EventHandler<GetLotteryTypeCompletedEventArgs>(_srvProxy_GetLotteryTypeCompleted);
			//_srvProxy.GetPfLoss_YKCompleted += new EventHandler<GetPfLoss_YKCompletedEventArgs>(_srvProxy_GetPfLoss_YKCompleted);
			_srvProxy.GetPfLoss_CZandTXCompleted += new EventHandler<GetPfLoss_CZandTXCompletedEventArgs>(_srvProxy_GetPfLoss_CZandTXCompleted);
			_srvProxy.GetPfLoss_TX_PctCompleted += new EventHandler<GetPfLoss_TX_PctCompletedEventArgs>(_srvProxy_GetPfLoss_TX_PctCompleted);
			_srvProxy.GetOverAllCfgCompleted += new EventHandler<GetOverAllCfgCompletedEventArgs>(_srvProxy_GetOverAllCfgCompleted);
			//_srvProxy.GetRejectOrderIDCompleted += new EventHandler<GetRejectOrderIDCompletedEventArgs>(_srvProxy_GetRejectOrderIDCompleted);
			RefreshTimer.Start();
			Connection();
		}

		public void SetKFUrl()
		{
			if (App.Session.Count != 0)
			{
				string url = Constant.KFSystem;
				lbKf.NavigateUri = new Uri(url);
			}
		}
		public void RefreshTimer_Tick(object sender, EventArgs e)
		{
			try
			{
				if (!App.Session.ContainsKey(Constant.USERNAME_SESSION) || App.Session[Constant.USERNAME_SESSION] == null ||
					!App.Session.ContainsKey(Constant.USERINFO_SESSION) || App.Session[Constant.USERINFO_SESSION] == null)
				{
					Messager.Show("网络故障或系统异常，请重新登录！");
					App.Navigation(new LoginPage());
				}
				RefreshConfig();
				RefreshMeneyAndOrdes();
				MsgShow();
			}
			catch
			{
				Messager.Show("网络故障或系统异常，请重新登录！");
				App.Navigation(new LoginPage());
			}
		}
		public void RefreshMeneyAndOrdes()
		{
			try
			{
				//dataForm1_Loaded(this.dataForm1, null);
				LoadUserCapital();
				if (mainBet == null)
					return;
				mainBet.RefreshGrid();

			}
			catch (Exception e)
			{
				throw e;
			}
		}
		public void MsgShow()
		{
			_srvProxy.GetPfLoss_CZandTXAsync(App.Session[Constant.USERNAME_SESSION].ToString());
			_srvProxy.GetPfLoss_TX_PctAsync(App.Session[Constant.USERNAME_SESSION].ToString());
			//_srvProxy.GetRejectOrderIDAsync(App.Session[Constant.USERNAME_SESSION].ToString());
			//_srvProxy.GetPfLoss_YKAsync(App.Session[Constant.USERNAME_SESSION].ToString());

		}

		//private void _srvProxy_GetRejectOrderIDCompleted(object sender, GetRejectOrderIDCompletedEventArgs e)
		//{
		//    if (e.Result.ToString().Trim() == string.Empty)
		//        return;
		//    Notify_Add("提现","您的提现申请(订单号："+e.Result.ToString()+")被拒绝!如有疑问,请联系在线客服！",DateTime.Now.ToShortDateString());
		//}

		public void _srvProxy_GetPfLoss_CZandTXCompleted(object sender, GetPfLoss_CZandTXCompletedEventArgs e)
		{
			List<ProfitLossInfo> list = e.Result.ToList();
			foreach (ProfitLossInfo p in list)
			{
				Notify_Add(p.ProfitLossType + "消息", p.Memo + "已处理,如有疑问,请联系在线客服！", p.ProfitLossTime.ToString());
			}
		}
		//public void _srvProxy_GetPfLoss_YKCompleted(object sender, GetPfLoss_YKCompletedEventArgs e)
		//{
		//    List<PfLossMsg> list = e.Result.ToList();
		//    foreach (PfLossMsg p in list)
		//    {
		//        string Content = p.LotteryName + p.IssueNo + "期派奖结束\n";
		//        Content += string.Format("您共有{0}条投注记录\n", p.RecordCount.ToString());
		//        Content += string.Format("本期净盈亏{0}元", p.ProfitLossMoney.ToString());
		//        Notify_Add(p.ProfitLossType + "提示", Content, p.ProfitLossTime);
		//    }
		//}
		void Notify_Add(string Title, string Content, string Time)
		{
			Size size = this.LayoutRoot.RenderSize;
			if (sp.ActualHeight + 85 >= size.Height)
			{
				return;
			}
			MsgNotify msg = new MsgNotify();
			msg.lbTime.Text = Time;
			msg.lbTitle.Text = Title;
			msg.lbContent.Text = Content;
			sp.Children.Add(msg);
			msg.btnClose.MouseLeftButtonDown += (s, e) =>
			{
				sp.Children.Remove(msg);
				_tip.HorizontalOffset = size.Width - 220;
				_tip.VerticalOffset = size.Height - (sp.Children.Count) * 85;
			};
			_tip.IsOpen = true;
			_tip.HorizontalOffset = size.Width - 220;
			_tip.VerticalOffset = size.Height - (sp.Children.Count) * 85;
		}
		void RefreshConfig()
		{
			try
			{
				LotteryServiceClient srv = WcfProxy.GetProxy;
				srv.GetPlayTypeNumCompleted += (s, er) =>
				{
					if (er.Result.Count != 0)
						App.Session[Constant.PLAYTYPENUM_SESSION] = er.Result.ToList();
				};
				srv.GetPlayTypeRadioCompleted += (s, er) =>
				{
					if (er.Result.Count != 0)
						App.Session[Constant.PLAYTYPERADIO_SESSION] = er.Result.ToList();
				};
				srv.GetPlayTypeInfoCompleted += (s, er) =>
				{
					if (er.Result.Count != 0)
						App.Session[Constant.PLAYTYPE_SESSION] = er.Result.ToList();
				};
				_srvProxy.GetOverAllCfgAsync();
				_srvProxy.GetLotteryTypeAsync();
				srv.GetPlayTypeInfoAsync();
				srv.GetPlayTypeNumAsync();
				srv.GetPlayTypeRadioAsync();
			}
			catch (Exception e)
			{
				throw e;
			}
		}
		void _srvProxy_GetOverAllCfgCompleted(object sender, GetOverAllCfgCompletedEventArgs e)
		{
			if (e.Result.Keys.Contains("MaxBetCount"))
				Constant.MaxBetCount = double.Parse(e.Result["MaxBetCount"]);

			if (e.Result.Keys.Contains("MaxBetMoney"))
				Constant.MaxBetMoney = double.Parse(e.Result["MaxBetMoney"]);

			if (e.Result.Keys.Contains("MinOneBetMoney"))
				Constant.MinOneBetMoney = double.Parse(e.Result["MinOneBetMoney"]);

			if (e.Result.Keys.Contains("MaxOneBetMoney"))
				Constant.MaxOneBetMoney = double.Parse(e.Result["MaxOneBetMoney"]);

			if (e.Result.Keys.Contains("MaxOutMoneyOneDay"))
				Constant.MaxOutMoneyOneDay = double.Parse(e.Result["MaxOutMoneyOneDay"]);

			if (e.Result.Keys.Contains("MaxOutMoneyOneTime"))
				Constant.MaxOutMoneyOneTime = double.Parse(e.Result["MaxOutMoneyOneTime"]);

			if (e.Result.Keys.Contains("MinOutMoneyOneTime"))
				Constant.MinOutMoneyOneTime = double.Parse(e.Result["MinOutMoneyOneTime"]);

			if (e.Result.Keys.Contains("MaxOutMoneyTimesOneDay"))
				Constant.MaxOutMoneyTimesOneDay = Convert.ToInt32(e.Result["MaxOutMoneyTimesOneDay"]);

			if (e.Result.Keys.Contains("MaxBonusPct"))
				Constant.MaxBonusPct = double.Parse(e.Result["MaxBonusPct"]);
			if (e.Result.Keys.Contains("KFSystem"))
			{
				Constant.KFSystem = e.Result["KFSystem"].ToString();
				SetKFUrl();
			}
			if (e.Result.Keys.Contains("MemBonusIncrement"))
			{
				Constant.MemBonusIncrement = Convert.ToDouble(e.Result["MemBonusIncrement"].ToString());
			}
		}
		void MainPage_Loaded(object sender, RoutedEventArgs e)
		{
			sp.Width = 200;
			sp.VerticalAlignment = VerticalAlignment.Bottom;
			sp.HorizontalAlignment = HorizontalAlignment.Right;
			_tip.Child = sp;
			SetKFUrl();
			if (!App.Session.ContainsKey(Constant.USERNAME_SESSION))
			{
				App.Navigation(new LoginPage());
				return;
			}
			LotteryServiceClient srv = WcfProxy.GetProxy;
			srv.GetUserInfoAsync(App.Session[Constant.USERNAME_SESSION].ToString());
			srv.GetUserInfoCompleted += (s, er) =>
			{
				if (er.Result == null)
				{
					Messager.Show("用户名不存在,请重新登录");
					App.Navigation(new LoginPage());
					return;
				}
				App.Session[Constant.USERINFO_SESSION] = er.Result;
				//_srvProxy.GetLotteryTypeAsync();
				InitPage();
				LoadUserCapital();
				//_srvProxy.GetOverAllCfgAsync();
			};
		}
		void _srvProxy_GetLotteryTypeCompleted(object sender, GetLotteryTypeCompletedEventArgs erg)
		{
			if (!App.Session.ContainsKey(Constant.LOTTERYPLAYTYPE_SESSION) ||
	 App.Session[Constant.LOTTERYPLAYTYPE_SESSION] == null)
			{
				App.Session[Constant.LOTTERYPLAYTYPE_SESSION] = erg.Result.ToList();
				InitPage();
			}
			else
			{
				List<LotteryTypeInfo> lastList = App.Session[Constant.LOTTERYPLAYTYPE_SESSION] as List<LotteryTypeInfo>;
				if (!Compare(lastList, erg.Result.ToList()))
				{
					App.Session[Constant.LOTTERYPLAYTYPE_SESSION] = erg.Result.ToList();
					InitPage();
				}
			}
		}
		void _srvProxy_GetPfLoss_TX_PctCompleted(object sender, GetPfLoss_TX_PctCompletedEventArgs e)
		{
			List<ProfitLossInfo> list = e.Result.ToList();
			foreach (ProfitLossInfo p in list)
			{
				Notify_Add(p.ProfitLossType + "消息", p.Memo + ",您得到佣金" + p.ProfitLossMoney + "元,已经充值到您的账户!", p.ProfitLossTime.ToString());
			}
		}
		void InitPage()
		{
			List<LotteryTypeInfo> list = App.Session[Constant.LOTTERYPLAYTYPE_SESSION] as List<LotteryTypeInfo>;
			if (list == null || list.Count == 0)
			{
				Messager.Show("系统故障,请联系客服!");
				App.Navigation(new LoginPage());
				return;
			}
			var result_p = from l in list
						   where l.Orientation == (int)LotteryOrientation.Positive
						   select l;
			if (result_p.Count() == 0)
				tb_P.Visibility = Visibility.Collapsed;
			else
				tb_P.Visibility = Visibility.Visible;
			foreach (LotteryTypeInfo l in result_p)
			{
				RadioButton rb = new RadioButton();
				rb.Height = 23;
				rb.Width = 75;
				rb.Content = l.LotteryName;
				rb.Tag = l.LotteryTypeID;
				rb.Style = App.Current.Resources["styleRadioButton_BetPlayType"] as Style;
				rb.Margin = new Thickness(1);
				rb.Checked += new RoutedEventHandler(buttonGroup_Checked);
				SP_Button_P.Children.Add(rb);
				if (list.First() == l)
					rb.IsChecked = true;
				else
					rb.IsEnabled = false;
			}
			var result_r = from l in list
						   where l.Orientation == (int)LotteryOrientation.Reverse
						   select l;
			if (result_r.Count() == 0)
				tb_R.Visibility = Visibility.Collapsed;
			else
				tb_R.Visibility = Visibility.Visible;
			foreach (LotteryTypeInfo l in result_r)
			{
				RadioButton rb = new RadioButton();
				rb.Height = 23;
				rb.Width = 75;
				rb.Content = l.LotteryName;
				rb.Tag = l.LotteryTypeID;
				rb.Style = App.Current.Resources["styleRadioButton_BetPlayType"] as Style;
				rb.Margin = new Thickness(1);
				rb.Checked += new RoutedEventHandler(buttonGroup_Checked);
				SP_Button_R.Children.Add(rb);
				if (list.First() == l && result_p.Count() == 0)
					rb.IsChecked = true;
				else
					rb.IsEnabled = false;
			}
			stkP = SP_Button_P;
			stkR = SP_Button_R;
			//buttonZxSSC.Tag = new LotteryView.SSC.Positive.ZSSC();
			//buttonZx3D.Tag = new LotteryView._3D.Positive.Z3D();
			//buttonZxSSQ.Tag = new LotteryView.SSQ.Positive.ZSSQ();
			//buttonNx3D.Tag = new LotteryView._3D.Reverse.N3D();
			//buttonNxSSC.Tag = new LotteryView.SSC.Reverse.NSSC();
			//buttonNxSSQ.Tag = new LotteryView.SSQ.Reverse.NSSQ();
			//buttonZxSSC.IsChecked = true;
		}
		private void image_MouseEnter(object sender, MouseEventArgs e)
		{
			Image image = (Image)sender;
			Border border = (Border)image.Parent;
			border.BorderBrush = new SolidColorBrush(Colors.Yellow);
		}

		private void image_MouseLeave(object sender, MouseEventArgs e)
		{
			Image image = (Image)sender;
			Border border = (Border)image.Parent;
			border.BorderBrush = null;
		}

		public void ClearChildren()
		{
			if (MainPanel.Children.Count > 0 && MainPanel.Children[0].GetType() == typeof(Controls.MainBet))
			{
				Controls.MainBet child = (Controls.MainBet)MainPanel.Children[0];
				child.XuanHaoPanel.Children.Clear();
			}
		}

		public void ClearMainPanel()
		{
			if (MainPanel.Children.Count > 0 && MainPanel.Children[0].GetType() == typeof(Controls.MainBet))
			{
				Controls.MainBet child = (Controls.MainBet)MainPanel.Children[0];
				child.XuanHaoPanel.Children.Clear();
			}
			mainBet = null;
			MainPanel.Children.Clear();
		}

		private void bt_money_Click(object sender, RoutedEventArgs e)
		{
			MoneyWindow mw = new MoneyWindow();
			mw.Closed += (s, er) =>
			{
				if (mw.WaitCount != -1)
				{
					if (mw.WaitCount > 0)
					{
						Notify_Add("排队消息", string.Format("您前面还有{0}笔提现,请耐心等候,给您带来不便请见谅!", mw.WaitCount), DateTime.Now.ToString());
					}
					else
						Notify_Add("提现消息", "客服人员即将为您处理,请您稍后查收!", DateTime.Now.ToString());
					//dataForm1_Loaded(null, null);
					LoadUserCapital();
				}
			};
			mw.Show();
			//_srvProxy.GetBankInfoAsync(App.Session[Constant.USERNAME_SESSION].ToString());
		}

		void _srvProxy_GetBankInfoCompleted(object sender, GetBankInfoCompletedEventArgs e)
		{
			if (e.Result == null)
			{
				Messager.Show("尚未设置银行资料,无法提现.[修改密码]->[银行资料]完成银行资料再提现.");
				return;
			}
			MoneyWindow mw = new MoneyWindow();
			mw.Closed += (s, er) =>
			{
				if (mw.WaitCount != -1)
				{
					if (mw.WaitCount > 0)
					{
						Notify_Add("排队消息", string.Format("您前面还有{0}笔提现,请耐心等候,给您带来不便请见谅!", mw.WaitCount), DateTime.Now.ToString());
					}
					else
						Notify_Add("提现消息", "客服人员即将为您处理,请您稍后查收!", DateTime.Now.ToString());
					//dataForm1_Loaded(null, null);
					LoadUserCapital();
				}
			};
			mw.Show();
		}

		private void bt_gamerecord_Click(object sender, RoutedEventArgs e)
		{
			SetBtnEnable();
			ClearMainPanel();
			ClearLotteryTypeChoosed();
			MainPanel.Children.Add(new GameRecord());
		}
		void SetBtnEnable()
		{
			if (SP_Button_P != null)
			{
				foreach (RadioButton rb in SP_Button_P.Children)
				{
					rb.IsEnabled = true;
				}
			}
			if (SP_Button_R != null)
			{
				foreach (RadioButton rb in SP_Button_R.Children)
				{
					rb.IsEnabled = true;
				}
			}
		}
		private void bt_profitlist_Click(object sender, RoutedEventArgs e)
		{
			SetBtnEnable();
			ClearMainPanel();
			ClearLotteryTypeChoosed();
			MainPanel.Children.Add(new ProfitList());
		}

		private void bt_lowerlist_Click(object sender, RoutedEventArgs e)
		{
			SetBtnEnable();
			ClearMainPanel();
			ClearLotteryTypeChoosed();
			MainPanel.Children.Add(new LowerList());
		}

		private void bt_chgpwd_Click(object sender, RoutedEventArgs e)
		{
			new ChgPwd().Show();
		}

		private void bt_exit_Click(object sender, RoutedEventArgs e)
		{
			_srvProxy.LoginOutAsync(App.Session[Constant.USERNAME_SESSION].ToString());
			if (kaijiang_timer != null && kaijiang_timer.IsEnabled == true)
			{
				kaijiang_timer.Stop();
			}
			if (RefreshTimer != null && RefreshTimer.IsEnabled == true)
			{
				RefreshTimer.Stop();
			}
			sp.Children.Clear();
			_tip.IsOpen = false;
			dicWs.Clear();
			App.Session.Clear();
			if (skt.Connected)
			{
				skt.Close();
				skt.Dispose();
			}
			App.Navigation(new LoginPage());
		}
		//切换彩种
		private void buttonGroup_Checked(object sender, RoutedEventArgs e)
		{
			if (MainPage.kaijiang_timer != null && MainPage.kaijiang_timer.IsEnabled == true)
			{
				MainPage.kaijiang_timer.Stop();
				MainPage.kaijiang_timer = null;
			}
			RadioButton rbtn = sender as RadioButton;
			foreach (RadioButton rb in SP_Button_P.Children)
			{
				if (rb != rbtn)
				{
					rb.IsChecked = false;
					//rb.IsEnabled = false; // lsyuan 不禁用
				}
			}
			foreach (RadioButton rb in SP_Button_R.Children)
			{
				if (rb != rbtn)
				{
					rb.IsChecked = false;
					//rb.IsEnabled = false; // lsyuan 不禁用
				}
			}
			Controls.MainBet MainBet;
			//if (MainPanel.Children.Count != 0 && MainPanel.Children[0] is Controls.MainBet)
			//{
			//    ClearChildren();
			//    MainBet = (Controls.MainBet)MainPanel.Children[0];
			//}
			//else
			//{
			ClearMainPanel();
			MainBet = new MainBet();
			MainPanel.Children.Add(MainBet);
			MainBet.LoadData();
			//}
			mainBet = MainBet;
			dicWs.Clear();
			LotteryTypeInfo ltype = (App.Session[Constant.LOTTERYPLAYTYPE_SESSION] as List<LotteryTypeInfo>).Where(p => p.LotteryTypeID == Convert.ToInt32(rbtn.Tag)).FirstOrDefault();
			if (ltype != null && ltype.IsOpen == 1)
			{
				ShowIsNotOpen();
				return;
			}
			switch ((LotteryType)(Convert.ToInt32(rbtn.Tag)))
			{
				case LotteryType.SSC:
					lotteryType = LotteryType.SSC;
					lotteryTypeAll = LotteryType.SSC;
					MainBet.XuanHaoPanel.Children.Add(new LotteryView.SSC.Positive.ZSSC());
					break;
				case LotteryType._3D:
					lotteryType = LotteryType._3D;
					lotteryTypeAll = LotteryType._3D;
					MainBet.XuanHaoPanel.Children.Add(new LotteryView._3D.Positive.Z3D());
					break;
				case LotteryType.SSQ:
					lotteryType = LotteryType.SSQ;
					lotteryTypeAll = LotteryType.SSQ;
					MainBet.XuanHaoPanel.Children.Add(new LotteryView.SSQ.Positive.ZSSQ());
					break;
				case LotteryType.SSCRX:
					lotteryType = LotteryType.SSC;
					lotteryTypeAll = LotteryType.SSCRX;
					MainBet.XuanHaoPanel.Children.Add(new LotteryView.SSC.RX.SSCRX());
					break;
				case LotteryType.NSSC:
					lotteryType = LotteryType.SSC;
					lotteryTypeAll = LotteryType.NSSC;
					MainBet.XuanHaoPanel.Children.Add(new LotteryView.SSC.Reverse.NSSC());
					break;
				case LotteryType.N3D:
					lotteryType = LotteryType._3D;
					lotteryTypeAll = LotteryType.N3D;
					MainBet.XuanHaoPanel.Children.Add(new LotteryView._3D.Reverse.N3D());
					break;
				case LotteryType.NSSQ:
					lotteryType = LotteryType.SSQ;
					lotteryTypeAll = LotteryType.NSSQ;
					MainBet.XuanHaoPanel.Children.Add(new LotteryView.SSQ.Reverse.NSSQ());
					break;
				default:
					ShowIsNotOpen();
					return;

			}
			LotteryServiceClient srv = WcfProxy.GetProxy;
			srv.GetRecentlyLotteryNumAsync((int)lotteryType);
			srv.GetRecentlyLotteryNumCompleted += (s, er) =>
				{
					if (er.Result.Count > 0)
					{
						MainBet.LotteryNum = er.Result[0].LotteryNums;
						MainBet.BallSize = Controls.BallSize.Big;
						MainBet.DataSource = er.Result.ToList();
						MainBet.CreateElement(er.Result[0].LotteryNums, Controls.BallSize.Big, er.Result.ToList());
						MainBet.RefreshGrid();
					}
				};

		}
		void ShowIsNotOpen()
		{
			Messager.Show("该彩种暂未开放!");
			foreach (RadioButton rb in SP_Button_P.Children)
			{
				rb.IsEnabled = true;
			}
			foreach (RadioButton rb in SP_Button_R.Children)
			{
				rb.IsEnabled = true;
			}
		}
		//public void dataForm1_Loaded(object sender, RoutedEventArgs e)
		//{
		//    //PersonalControl = dataForm1;
		//    LotteryServiceClient srv = WcfProxy.GetProxy;
		//    srv.GetCapitalInfoAsync(App.Session[Constant.USERNAME_SESSION].ToString());
		//    srv.GetCapitalInfoCompleted += (s, er) =>
		//    {
		//        dataForm1.CurrentItem = er.Result;
		//    };
		//}
		public void LoadUserCapital()
		{
			PersonalControl = gridUserInfo;
			LotteryServiceClient srv = WcfProxy.GetProxy;
			srv.GetCapitalInfoAsync(App.Session[Constant.USERNAME_SESSION].ToString());
			srv.GetCapitalInfoCompleted += (s, er) =>
			{
				gridUserInfo.DataContext = er.Result;
			};

		}
		void ClearLotteryTypeChoosed()
		{
			foreach (RadioButton rb in SP_Button_P.Children)
			{
				rb.IsChecked = false;
			}
			foreach (RadioButton rb in SP_Button_R.Children)
			{
				rb.IsChecked = false;
			}
		}
		void LayoutRoot_SizeChanged(object sender, SizeChangedEventArgs e)
		{
			_tip.HorizontalOffset = e.NewSize.Width - 220;
			_tip.VerticalOffset = e.NewSize.Height - sp.Children.Count * 85;
		}
		bool Compare(List<LotteryTypeInfo> lastList, List<LotteryTypeInfo> nowList)
		{
			if (lastList.Count != nowList.Count)
				return false;
			foreach (LotteryTypeInfo info in nowList)
			{
				LotteryTypeInfo lastInfo = nowList.Where(c => c.LotteryTypeID == info.LotteryTypeID).FirstOrDefault();
				if (lastInfo == null)
					return false;
				if (lastInfo.Orientation != info.Orientation
					|| lastInfo.LotteryName != info.LotteryName
					|| lastInfo.IsEnable != info.IsEnable)
					return false;
			}
			return true;
		}

		void CreateVodio()
		{
			media = new MediaElement();
			media.Height = 0;
			media.Width = 0;
			media.Volume = 1;
			media.AutoPlay = false;
			media.Source = new Uri("msg.mp3", UriKind.Relative);
			LayoutRoot.Children.Add(media);
		}

		#region Socket操作
		/// <summary>
		/// 连接到scoket服务器
		/// </summary>
		void Connection()
		{
			try
			{
				if (skt == null)
				{
					// 实例化 Socket
					skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				}

				if (skt.Connected) { skt.Close(); }

				// 实例化 SocketAsyncEventArgs ，用于对 Socket 做异步操作，很方便
				SocketAsyncEventArgs args = new SocketAsyncEventArgs();
				// 服务器的 EndPoint
				args.RemoteEndPoint = new DnsEndPoint(Constant.SocketIp, Constant.SocketPort);
				// 异步操作完成后执行的事件
				args.Completed += new EventHandler<SocketAsyncEventArgs>(OnSocketConnectCompleted);

				// 异步连接服务端
				skt.ConnectAsync(args);

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
				//OutPut(ex.Message.ToString());
			}
		}
		/// <summary>
		/// 连接完成回调处理
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void OnSocketConnectCompleted(object sender, SocketAsyncEventArgs e)
		{
			SendArgs.RemoteEndPoint = e.RemoteEndPoint;
			SendArgs.Completed += new EventHandler<SocketAsyncEventArgs>(SendArgs_Completed);

			try
			{
				SendText("0," + App.Session[Constant.USERNAME_SESSION].ToString() + ",");
				//显示连接结果
				if (skt.Connected)//连接失败
				{
					SocketAsyncEventArgs args = new SocketAsyncEventArgs();
					args.RemoteEndPoint = e.RemoteEndPoint;

					// 设置数据缓冲区
					byte[] buffer = new byte[1024];
					args.SetBuffer(buffer, 0, buffer.Length);

					args.Completed += new EventHandler<SocketAsyncEventArgs>(OnSocketReceiveCompleted);
					// 异步地从服务端 Socket 接收数据
					skt.ReceiveAsync(args);
				}
			}
			catch (Exception ex)
			{
				//OutPut(ex.Message.ToString());
			}
		}

		/// <summary>
		/// 发送完成后的回调函数
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		void SendArgs_Completed(object sender, SocketAsyncEventArgs e)
		{
			//OutPut("发送结果：" + e.SocketError.ToString());
		}

		/// <summary>
		/// 接受服务端发来的数据-回调处理
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void OnSocketReceiveCompleted(object sender, SocketAsyncEventArgs e)
		{
			try
			{
				for (int i = e.Offset; i < e.BytesTransferred; i++)
				{
					ReceiveBytes[i] = e.Buffer[i];
				}
				string[] SrvResult = Encoding.UTF8.GetString(ReceiveBytes, 0, e.Buffer.Length).Split(',');
				switch (int.Parse(SrvResult[0]))
				{
					case (int)CommandType.MakeOffLine:
						if (!MakeOffLine)
						{
							this.Dispatcher.BeginInvoke(
							() =>
							{
								if (kaijiang_timer != null && kaijiang_timer.IsEnabled == true)
								{
									kaijiang_timer.Stop();
								}
								if (RefreshTimer != null && RefreshTimer.IsEnabled == true)
								{
									RefreshTimer.Stop();
								}
								sp.Children.Clear();
								_tip.IsOpen = false;
								dicWs.Clear();
								App.Session.Clear();
								if (skt.Connected)
								{
									skt.Close();
									skt.Dispose();
								}
								Messager.Show("您的账号在另外一个地方上线,您被迫下线!");
								App.Navigation(new LoginPage());
							});
							MakeOffLine = true;
						}
						break;
					default:
						break;
				}
			}
			catch (Exception ex)
			{
				//OutPut(ex.Message.ToString());
			}

			// 继续异步地从服务端 Socket 接收数据(类似长连接)
			if (skt.Connected)
			{
				skt.ReceiveAsync(e);
			}
			else
			{
				//OutPut("无法连接到服务器...请刷新后再试...");
			}
		}
		/// <summary>
		/// 发送文本消息
		/// </summary>
		void SendText(string strTxt)
		{
			if (skt.Connected)
			{
				byte[] bTxt = UTF8Encoding.UTF8.GetBytes(strTxt);

				//设置需要发送的数据的缓冲区   
				List<ArraySegment<byte>> _lst = new List<ArraySegment<byte>>();
				_lst.Add(new ArraySegment<byte>(bTxt));
				SendArgs.BufferList = _lst;

				//SendArgs.UserToken
				// 异步地向服务端 Socket 发送消息
				skt.SendAsync(SendArgs);
			}
			else
			{
				//OutPut("无法连接到服务器...请刷新后再试...");
			}
		}
		#endregion
		private void lbKf_Click(object sender, RoutedEventArgs e)
		{


		}
	}
}
